package service

import (
	"errors"
	"gin_tem/global"
	"gin_tem/internal/dto"
	"gin_tem/internal/model"
	"gin_tem/middlewares"
	"gin_tem/utils"
	"gorm.io/gorm"
)

type UserService interface {
	// CreateUser 用户注册
	CreateUser(req *dto.CreateUserRequest) error
	//Login 用户登录
	Login(req *dto.LoginUserRequest) (*dto.LoginUserResponse, error)
	List() (*[]dto.ListUserResponse, error)
}
type userService struct {
	db *gorm.DB
}

func NewUserService(db *gorm.DB) UserService {
	return &userService{db: db}
}

// CreateUser 注册
func (s *userService) CreateUser(req *dto.CreateUserRequest) error {
	s.db.AutoMigrate(&model.User{})
	hashedPassword := utils.Hmac(global.Config.Md5.Key, req.Password)
	user := &model.User{
		Account:  req.Account,
		Password: hashedPassword,
	}
	tx := s.db.Where("account = ?", req.Account).Find(&model.User{})
	if tx.RowsAffected == 1 {
		return errors.New("账号已存在")
	}
	result := s.db.Create(user)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

// Login 登录
func (s *userService) Login(req *dto.LoginUserRequest) (*dto.LoginUserResponse, error) {
	hashedPassword := utils.Hmac(global.Config.Md5.Key, req.Password)
	user := &model.User{}
	result := s.db.Where("account = ? AND password = ?", req.Account, hashedPassword).Find(&user)
	if result.Error != nil {
		return nil, result.Error
	}
	if result.RowsAffected == 0 {
		return nil, errors.New("用户名或密码错误")
	}
	if token, err := middlewares.GenToken(int(user.ID)); err != nil {
		return nil, err
	} else {
		return &dto.LoginUserResponse{
			Account: user.Account,
			ID:      int(user.ID),
			Token:   token,
		}, nil
	}
}

// List 查询所有用户
func (s *userService) List() (*[]dto.ListUserResponse, error) {
	userList := &[]model.User{}
	var list []dto.ListUserResponse
	result := s.db.Find(userList).Scan(&list)
	if result.Error != nil {
		return nil, result.Error
	}
	return &list, nil
}
